package com.atung.parking.service.impl;

import com.atung.parking.config.auth.PwdCreateUtil;
import com.atung.parking.config.result.ApiResult;
import com.atung.parking.config.result.PageInfoResponse;
import com.atung.parking.controller.DateConvertUtil;
import com.atung.parking.entity.BusApprovalRecord;
import com.atung.parking.entity.BusSuperUser;
import com.atung.parking.enums.AdminType;
import com.atung.parking.enums.ApprovalModelType;
import com.atung.parking.enums.ExportType;
import com.atung.parking.enums.SuperUserState;
import com.atung.parking.export.PublicExportUtil;
import com.atung.parking.export.SuperAdminExportVO;
import com.atung.parking.mapper.BusApprovalRecordMapper;
import com.atung.parking.mapper.BusSuperUserMapper;
import com.atung.parking.mapstruct.ParkingIotPackageConverter;
import com.atung.parking.mapstruct.SuperUserConverter;
import com.atung.parking.request.query.QuerySuperUserRequest;
import com.atung.parking.request.save.SaveOrUpdateSuperUserRequest;
import com.atung.parking.request.save.UpdateSuperUserStateRequest;
import com.atung.parking.response.page.ApprovalRecordResponse;
import com.atung.parking.response.page.SimpleSuperUserResponse;
import com.atung.parking.service.SuperUserManegeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
public class SuperUserManegeServiceImpl implements SuperUserManegeService {
    @Resource
    private BusSuperUserMapper busSuperUserMapper;
    @Resource
    private SuperUserConverter superUserConverter;
    @Resource
    private PublicExportUtil publicExportUtil;
    @Resource
    private BusApprovalRecordMapper busApprovalRecordMapper;
    @Resource
    private ParkingIotPackageConverter parkingIotPackageConverter;


    @Override
    @Transactional
    public ApiResult saveSuperUserService(SaveOrUpdateSuperUserRequest request, HttpServletRequest httpServletRequest) {
        BusSuperUser busSuperUser = new BusSuperUser();
        BusSuperUser busSuperUserByPhone = queryBusSuperByPhoneService(request.getPhone());
        BusSuperUser busSuperUserByUsername = queryBusSuperByUsernameService(request.getUsername());
        //获取手机号 和配置账号
        if (Objects.nonNull(request.getId())) {
            BusSuperUser dbBusSuperUser = busSuperUserMapper.selectById(request.getId());
            if (Objects.isNull(dbBusSuperUser)) {
                return ApiResult.fail("数据不存在");
            }
        } else {
            if (Objects.nonNull(busSuperUserByPhone)) {
                return ApiResult.fail("手机号重复");
            }
            if (Objects.nonNull(busSuperUserByUsername)) {
                return ApiResult.fail("用户名重复");
            }
            BeanUtils.copyProperties(request, busSuperUser);
            String salt = PwdCreateUtil.createSalt();
            busSuperUser.setSalt(salt);
            busSuperUser.setPassword(PwdCreateUtil.createPwd(request.getPassword(), salt));
            busSuperUser.setStatus(SuperUserState.NORMAL.ordinal());
            busSuperUser.setType(AdminType.ADMIN.ordinal());
        }
        busSuperUserMapper.insert(busSuperUser);
        BusApprovalRecord busApprovalRecord = new BusApprovalRecord();
        busApprovalRecord.setApprovalType("新增客户");
        busApprovalRecord.setModelType(ApprovalModelType.SUPER_ADMIN.name());
        busApprovalRecord.setModelId(busSuperUser.getId());
        this.saveApprovalRecord(busApprovalRecord);
        return ApiResult.ok();
    }

    @Override
    public ApiResult updateSuperUserStateService(UpdateSuperUserStateRequest request) {
        BusSuperUser dbBusSuperUser = busSuperUserMapper.selectById(request.getId());
        if (Objects.isNull(dbBusSuperUser)) {
            return ApiResult.fail("数据不存在");
        }
        dbBusSuperUser.setStatus(request.getState().ordinal());
        busSuperUserMapper.updateById(dbBusSuperUser);

        String approvalType = request.getState().equals(SuperUserState.NORMAL) ? "启用" : "禁用";
        BusApprovalRecord busApprovalRecord = new BusApprovalRecord();
        busApprovalRecord.setApprovalType(approvalType);
        busApprovalRecord.setModelType(ApprovalModelType.SUPER_ADMIN.name());
        busApprovalRecord.setModelId(dbBusSuperUser.getId());
        this.saveApprovalRecord(busApprovalRecord);
        return ApiResult.ok();
    }

    @Override
    public PageInfoResponse<BusSuperUser> querySuperUserListService(QuerySuperUserRequest request) {

        QueryWrapper<BusSuperUser> queryWrapper = createQueryWrapper(request);
        Page<BusSuperUser> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<BusSuperUser> busSuperUserPage = busSuperUserMapper.selectPage(page, queryWrapper);
        PageInfoResponse<BusSuperUser> pageInfoResponse = new PageInfoResponse<>();
        pageInfoResponse.setTotal(busSuperUserPage.getTotal());
        pageInfoResponse.setData(busSuperUserPage.getRecords());
        return pageInfoResponse;
    }


    public QueryWrapper<BusSuperUser> createQueryWrapper(QuerySuperUserRequest request) {
        QueryWrapper<BusSuperUser> queryWrapper = new QueryWrapper<>();
        //状态
        if (Objects.nonNull(request.getUserState())) {
            queryWrapper.eq("status", request.getUserState().ordinal());
        }
        //客户名称
        if (StringUtils.hasText(request.getName())) {
            queryWrapper.like("name", request.getName());
        }
        //联系电话
        if (StringUtils.hasText(request.getPhone())) {
            queryWrapper.like("phone", request.getPhone());
        }
        //账号
        if (StringUtils.hasText(request.getUsername())) {
            queryWrapper.like("username", request.getUsername());
        }
        //时间查询
        if (StringUtils.hasText(request.getStartData()) && StringUtils.hasText(request.getEndData())) {
            Long start = DateConvertUtil.convertQueryStartToMillis(request.getStartData());
            Long end = DateConvertUtil.convertQueryEndToMillis(request.getEndData());
            if (Objects.nonNull(request.getStartData()) && Objects.nonNull(request.getEndData())) {
                queryWrapper.between("creator_time", start, end);
            }

        }
        queryWrapper.eq("type", AdminType.ADMIN.ordinal());
        queryWrapper.orderByDesc("creator_time");
        return queryWrapper;
    }

    @Override

    public BusSuperUser queryBusSuperByPhoneService(String phone) {
        QueryWrapper<BusSuperUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        BusSuperUser busSuperUser = busSuperUserMapper.selectOne(queryWrapper);
        return busSuperUser;
    }

    @Override
    public BusSuperUser queryBusSuperByIdService(Long id) {
        return busSuperUserMapper.selectById(id);
    }

    @Override
    public List<SimpleSuperUserResponse> querySuperUserNameListService() {
        QueryWrapper<BusSuperUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", AdminType.ADMIN.ordinal());
        queryWrapper.orderByDesc("creator_time");
        return busSuperUserMapper.selectList(queryWrapper).stream().map(item -> SimpleSuperUserResponse.builder()
                .name(item.getName())
                .id(item.getId())
                .build()).collect(Collectors.toList());
    }

    @Override
    public void exportSuperUserListService(QuerySuperUserRequest request, HttpServletResponse httpServletResponse) {
        QueryWrapper<BusSuperUser> queryWrapper = createQueryWrapper(request);
        List<BusSuperUser> busSuperUserPage = busSuperUserMapper.selectList(queryWrapper);
        List<SuperAdminExportVO> collect = busSuperUserPage.stream().map(item -> {
            SuperAdminExportVO superUserResponse = superUserConverter.toExportVo(item);
            superUserResponse.setStatus(item.getStatus().equals(SuperUserState.NORMAL.ordinal()) ? "正常" : "禁用");
            FastDateFormat formatter = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
            // 格式化日期时间
            try {
                String formattedDate = formatter.format(Long.valueOf(item.getCreatorTime()));
                superUserResponse.setCreatorTime(formattedDate);
            } catch (Exception e) {
                superUserResponse.setCreatorTime("时间格式化出现问题");
            }
            return superUserResponse;

        }).collect(Collectors.toList());
        try {
            publicExportUtil.exportReport(ExportType.CUSTOMER_EXPORT, collect, httpServletResponse);
        } catch (Exception e) {

        }
    }

    @Override
    public List<ApprovalRecordResponse> queryApprovalSuperAdminListService(Long id) {
        QueryWrapper<BusApprovalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model_id", id);
        queryWrapper.eq("model_type", ApprovalModelType.SUPER_ADMIN.name());
        List<BusApprovalRecord> approvalRecords = busApprovalRecordMapper.selectList(queryWrapper);
        return approvalRecords.stream().map(parkingIotPackageConverter::toApprovalResponse).collect(Collectors.toList());

    }

    public BusSuperUser queryBusSuperByUsernameService(String username) {
        QueryWrapper<BusSuperUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        BusSuperUser busSuperUser = busSuperUserMapper.selectOne(queryWrapper);
        return busSuperUser;
    }

    public void saveApprovalRecord(BusApprovalRecord busApprovalRecord) {
        busApprovalRecordMapper.insert(busApprovalRecord);
    }

}
